<template>
  <div class="permission-management">
    <el-tabs v-model="activeTab" class="permission-tabs">
      <el-tab-pane label="角色管理" name="roles">
        <el-card class="role-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">角色列表</span>
              <el-button type="primary" @click="handleAddRole">
                <el-icon><Plus /></el-icon>添加角色
              </el-button>
            </div>
          </template>

          <el-table 
            :data="roles" 
            v-loading="loading"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="角色名称" />
            <el-table-column prop="code" label="角色标识" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="250" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button type="primary" size="small" @click="handleEditRole(row)">
                    <el-icon><Edit /></el-icon>编辑
                  </el-button>
                  <el-button type="success" size="small" @click="handleAssignPermissions(row)">
                    <el-icon><Setting /></el-icon>分配权限
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteRole(row)">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="权限管理" name="permissions">
        <el-card class="permission-card">
          <template #header>
            <div class="card-header">
              <span class="card-title">权限列表</span>
              <el-button type="primary" @click="handleAddPermission">
                <el-icon><Plus /></el-icon>添加权限
              </el-button>
            </div>
          </template>

          <el-table
            :data="permissions"
            row-key="id"
            :tree-props="{ children: 'children' }"
            v-loading="loading"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="name" label="权限名称" />
            <el-table-column prop="type" label="类型" width="120">
              <template #default="{ row }">
                <el-tag :type="row.type === 'menu' ? 'success' : 'info'">
                  {{ row.type === 'menu' ? '菜单' : '按钮' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="path" label="路径" />
            <el-table-column prop="permission" label="权限标识" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button type="primary" size="small" @click="handleEditPermission(row)">
                    <el-icon><Edit /></el-icon>编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeletePermission(row)">
                    <el-icon><Delete /></el-icon>删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 角色对话框 -->
    <el-dialog
      v-model="roleDialog.visible"
      :title="roleDialog.type === 'add' ? '添加角色' : '编辑角色'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="roleDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleRoleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限对话框 -->
    <el-dialog
      v-model="permissionDialog.visible"
      :title="permissionDialog.type === 'add' ? '添加权限' : '编辑权限'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="80px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
          </el-select>
        </el-form-item>
        <el-form-item label="路径" prop="path" v-if="permissionForm.type === 'menu'">
          <el-input v-model="permissionForm.path" placeholder="请输入路径" />
        </el-form-item>
        <el-form-item label="权限标识" prop="permission">
          <el-input v-model="permissionForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="permissions"
            :props="{ label: 'name', value: 'id' }"
            placeholder="请选择上级权限"
            style="width: 100%"
            clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      v-model="assignDialog.visible"
      title="分配权限"
      width="500px"
      destroy-on-close
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissions"
        :props="{ label: 'name' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="assignDialog.checkedKeys"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Setting } from '@element-plus/icons-vue'

// 选项卡激活状态
const activeTab = ref('roles')

// 加载状态
const loading = ref(false)

// 角色数据
const roles = ref([
  {
    id: 1,
    name: '超级管理员',
    code: 'SUPER_ADMIN',
    description: '系统超级管理员，拥有所有权限',
    createTime: '2024-03-25 10:00:00'
  },
  {
    id: 2,
    name: '普通用户',
    code: 'USER',
    description: '普通用户，拥有基本权限',
    createTime: '2024-03-25 10:00:00'
  }
])

// 权限数据
const permissions = ref([
  {
    id: 1,
    name: '系统管理',
    type: 'menu',
    path: '/system',
    permission: 'system',
    children: [
      {
        id: 2,
        name: '用户管理',
        type: 'menu',
        path: '/system/users',
        permission: 'system:user'
      },
      {
        id: 3,
        name: '角色管理',
        type: 'menu',
        path: '/system/roles',
        permission: 'system:role'
      }
    ]
  }
])

// 角色对话框
const roleDialog = reactive({
  visible: false,
  type: 'add' // 'add' 或 'edit'
})

// 角色表单
const roleFormRef = ref(null)
const roleForm = ref({
  name: '',
  code: '',
  description: ''
})

// 角色表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 权限对话框
const permissionDialog = reactive({
  visible: false,
  type: 'add' // 'add' 或 'edit'
})

// 权限表单
const permissionFormRef = ref(null)
const permissionForm = ref({
  name: '',
  type: 'menu',
  path: '',
  permission: '',
  parentId: null
})

// 权限表单验证规则
const permissionRules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  permission: [
    { required: true, message: '请输入权限标识', trigger: 'blur' }
  ]
}

// 分配权限对话框
const assignDialog = reactive({
  visible: false,
  roleId: null,
  checkedKeys: []
})

const permissionTreeRef = ref(null)

// 添加角色
const handleAddRole = () => {
  roleDialog.type = 'add'
  roleDialog.visible = true
  roleForm.value = {
    name: '',
    code: '',
    description: ''
  }
}

// 编辑角色
const handleEditRole = (row) => {
  roleDialog.type = 'edit'
  roleDialog.visible = true
  roleForm.value = { ...row }
}

// 删除角色
const handleDeleteRole = (row) => {
  ElMessageBox.confirm(
    '确认删除该角色吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // TODO: 调用删除角色API
    ElMessage.success('删除成功')
  })
}

// 提交角色表单
const handleRoleSubmit = async () => {
  if (!roleFormRef.value) return

  try {
    await roleFormRef.value.validate()
    // TODO: 调用添加/编辑角色API
    ElMessage.success(roleDialog.type === 'add' ? '添加成功' : '更新成功')
    roleDialog.visible = false
  } catch (error) {
    console.error('Role form error:', error)
  }
}

// 添加权限
const handleAddPermission = () => {
  permissionDialog.type = 'add'
  permissionDialog.visible = true
  permissionForm.value = {
    name: '',
    type: 'menu',
    path: '',
    permission: '',
    parentId: null
  }
}

// 编辑权限
const handleEditPermission = (row) => {
  permissionDialog.type = 'edit'
  permissionDialog.visible = true
  permissionForm.value = { ...row }
}

// 删除权限
const handleDeletePermission = (row) => {
  ElMessageBox.confirm(
    '确认删除该权限吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    // TODO: 调用删除权限API
    ElMessage.success('删除成功')
  })
}

// 提交权限表单
const handlePermissionSubmit = async () => {
  if (!permissionFormRef.value) return

  try {
    await permissionFormRef.value.validate()
    // TODO: 调用添加/编辑权限API
    ElMessage.success(permissionDialog.type === 'add' ? '添加成功' : '更新成功')
    permissionDialog.visible = false
  } catch (error) {
    console.error('Permission form error:', error)
  }
}

// 分配权限
const handleAssignPermissions = (row) => {
  assignDialog.visible = true
  assignDialog.roleId = row.id
  // TODO: 获取角色已有权限
  assignDialog.checkedKeys = [1, 2]
}

// 提交分配权限
const handleAssignSubmit = async () => {
  if (!permissionTreeRef.value) return

  const checkedKeys = permissionTreeRef.value.getCheckedKeys()
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]

  // TODO: 调用分配权限API
  console.log('分配权限:', allCheckedKeys)
  ElMessage.success('分配成功')
  assignDialog.visible = false
}
</script>

<style scoped>
.permission-management {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.permission-tabs {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.role-card,
.permission-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
  padding: 0 20px;
  background-color: #fff;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  padding: 0;
}

:deep(.el-button-group .el-button) {
  margin-left: 0;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node__label) {
  font-size: 14px;
}

.el-button-group {
  .el-button {
    margin-right: 8px;
    &:last-child {
      margin-right: 0;
    }
  }
}
</style> 